<template>
  <el-dialog
    class="assign-role"
    title="分配角色"
    :visible="showRoleDialog"
    :close-on-click-modal="false"
    @close="closeDialog"
    @open="openDialog"
  >
    <!-- 这里准备复选框 -->
    <el-checkbox-group v-model="checkList" v-loading="loading">
      <el-checkbox v-for="(item,index) in RoleList" :key="index" :label="item.id">{{ item.name }}</el-checkbox>
    </el-checkbox-group>
    <template #footer>
      <el-button type="primary" size="small" @click="assignRole">确定</el-button>
      <el-button size="small" @click="closeDialog">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { getRoleList } from '@/api/setting'
import { getBaseUserInfoApi } from '@/api/user'
import { assignRolesApi } from '@/api/emploess'
export default {
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    // 用户的id 用来查询当前用户的角色信息
    userId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      RoleList: [],
      checkList: [],
      loading: false
    }
  },
  methods: {
    closeDialog() {
      this.$emit('update:showRoleDialog', false)
    },
    openDialog() {
      this.loading = true
      // Promise.all：当数组里的请求都成功之后再执行then方法s
      // 当两个请求都有结果的时候再把loading设置为false
      Promise.all([this.getRole(), this.getBaseUserInfo()]).then(res => {
        this.loading = false
      })
    },
    // 获取所有权限
    async getRole() {
      const { data: { rows }} = await getRoleList(1, 9999)
      console.log(rows)
      this.RoleList = rows
    },
    // 获取用户现在拥有的权限
    async getBaseUserInfo() {
      const { data: { roleIds }} = await getBaseUserInfoApi(this.userId)
      console.log(roleIds)
      this.checkList = roleIds
    },
    async assignRole() {
      const res = await assignRolesApi({
        id: this.userId,
        roleIds: this.checkList
      })
      console.log('分配权限成功', res)
      this.$message.success('分配权限成功')
      // 关闭弹框
      this.closeDialog()
    }
  }
}
</script>
<style lang="scss" scoped>
.assign-role {
  ::v-deep {
    .el-checkbox {
      font-size: 30px;
    }
  }
}
</style>
